<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller {

    //用户控制器 主要用于 注册 登录 退出等
    /*
    public function index(){
        $data['title']='会员中心 找金银网';
        $this->assign("data", $data);
        $this->display();
    }*/
    //报价
    public function reg(){
        //如果已登录，则跳转到后台首页
        if(session('member_id')||cookie('member_id')){
            echo "<script>alert('您已经登录，请您退出当前账号再注册');window.location.href='/home/index/'</script>";exit;
        }
        $data['title']='注册 找金银网';
        $this->assign("data", $data);
        $this->display();
    }
    //注册用户 提交  先转换36进制，先注册到本地，注册无误后同步到UC 测试注册流程!!! 先测试邮箱注册!
    public function reg_post(){
        //邮箱注册
        if ($_POST['regtype']==1){
            if($_POST['member_email']==''||$_POST['member_passwd']==''||$_POST['re_member_passwd']==''){
                echo "<script>alert('请您填写完整后尝试重新提交');history.back(-1);</script>";exit;
            }
            if($_POST['re_member_passwd']!=$_POST['member_passwd']){
                echo "<script>alert('两次输入的密码不一致，请您尝试重新输入或者联系客服人员');history.back(-1);</script>";exit;
            }
            //验证码验证
            /*$verify = new \Think\Verify();
            $passcode=addslashes($_POST['passcode']);
            if($verify->check($passcode, '')==false){
                echo "<script>alert('验证码错误');history.back(-1);</script>";exit;
            }*/
            //邮箱格式验证
            if ( isset($_POST["member_email"]) ){
                $email_address = $_POST["member_email"];
                $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
                if ( !preg_match( $pattern, $email_address ) )
                {
                    echo "<script>alert('邮箱格式不正确');history.back(-1);</script>";exit;
                }
            }
            //检测邮箱是否已被注册 此处修改为连接到UC检测
            $post=I('post.');
            $Model=D("Member");
            $Model->post=$post;
            if($Model->check_email_exist()){
                echo "<script>alert('此邮箱已经被注册，请您尝试重新输入或者联系客服人员');history.back(-1);</script>";exit;
            }
            //写入UC 确保uid唯一
            $uc_username=$this->get_uc_username();
            //echo $uc_username;exit;
            $data['username']=$uc_username;
            $data['password']=md5($post['member_passwd']);
            $data['usertype']=1;   //1B2B 2B2C 3P2B
            $data['email']=$post['member_email'];
            vendor('Ucenter.UcApi');//载入UcApi扩展
            $uid=UcApi::reg($data);  //UID
            if($uid<=0){
                echo "<script>alert('注册失败');history.back(-1);</script>";
            }
            //echo $uid;exit;
            //获取uid,写入本地数据库
            $count=$Model->where('member_id='.$uid)->count();
            if($count>0){ //删除
                $Model->where('member_id='.$uid)->delete();
            }else{ //写入
                $post_data['member_id']=$uid;
                $post_data['uc_username']=$uc_username;
                $post_data['uc_usertype']=1;  //1B2B 2B2C 3P2B
                $post_data['member_passwd']=md5($post['member_passwd']);
                $post_data['member_email']=$post['member_email'];
                $post_data['member_reg_time']=time();
                $Model->post=$post_data;
                if(!$Model->user_add_post()){
                    echo "<script>alert('提交失败，请您尝试重新提交');history.back(-1);</script>";exit;
                }
            }
            //注册成功后，自动登录并跳转至首页
            //设置session cookie
            session('member_id',$uid);
            session('member_email',$post['member_email']);
            cookie('member_id',$uid,3600);
            cookie('member_email',$post['member_email'],3600);
            //dump(session()).'<br />'.dump(cookie());exit;
            echo "<script>window.location.href='/home/index/';</script>";
        }
        //手机注册
        /*if ($_POST['regtype']==2){
            //是否填写完毕
            if($_POST['member_mobile']==''||$_POST['member_passwd']==''){
                echo "<script>alert('请您填写完整后尝试重新提交');history.back(-1);</script>";exit;
            }
            //验证码验证
            $verify = new \Think\Verify();
            $passcode=addslashes($_POST['passcode']);
            if($verify->check($passcode, '')==false){
                echo "<script>alert('验证码错误');history.back(-1);</script>";exit;
            }
            //电话格式验证
            if ( isset($_POST["member_mobile"]) )
            {
                $phonenum = $_POST["member_mobile"];
                $pattern = "/1\d{10}/";
                if ( !preg_match( $pattern, $phonenum ) )
                {
                    echo "<script>alert('手机号格式不正确');history.back(-1);</script>";exit;
                }
            }
            //短信验证码
            if(!($_POST['relcode']==$_POST['phone_code'] && $_POST['phone_code']<>'')){
                echo "<script>alert('短信验证码错误');history.back(-1);</script>";exit;
            }
        }*/
    }
    //登录
    public function login(){
        //如果已登录，则跳转到后台首页
        if(session('member_id')||cookie('member_id')){
            echo "<script>alert('您已经登录，点击确认回到首页');window.location.href='/home/index/'</script>";exit;
        }
        $data['title']='登录 找金银网';
        $this->assign("data", $data);
        $this->display();
    }
    //登录提交 修改为先本地登录 再异步推到UC
    public function login_post(){
        //如果已登录，则跳转到后台首页
        if(session('member_id')||cookie('member_id')){
            echo "<script>alert('您已经登录，点击确认回到首页');window.location.href='/home/index/'</script>";exit;
        }
        if($_POST['member_email']==''||$_POST['member_passwd']==''){
            echo "<script>alert('请您填写完整后尝试重新提交');history.back(-1);</script>";exit;
        }
        //邮箱格式验证
        if ( isset($_POST["member_email"]) )
        {
            $email_address = $_POST["member_email"];
            $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
            if ( !preg_match( $pattern, $email_address ) )
            {
                echo "<script>alert('邮箱格式不正确');history.back(-1);</script>";exit;
            }
        }
        //print_r($_POST);exit;
        //先登录本地，再推送UC同步
        $post['member_email']=I('post.member_email');
        $post['member_passwd']=md5(I('post.member_passwd'));
        //print_r($post);exit;
        $Member=D("Member");
        $Member->post=$post;
        if(!$Member->check_email_login()){
            //echo 82929;exit;
            //本地登录失败，则登录UC查询用户并同步到本地数据库
            //连接UC端
            $UC=M('Members','uc_','DB_CONFIG');
            $where['email']=$post['member_email'];
            $where['passwd']=$post['member_passwd'];
            //$where['member_state']=1; //1为启用2为关闭
            $where['_logic'] = 'and';
            $count=$UC->where($where)->count();
            //echo $count;exit;
            if($count==0){
                echo "<script>alert('用户名/密码错误或者您的账号已被停用，请您尝试重新输入或者联系客服人员');history.back(-1);</script>";exit;
            }
            //登录成功后
            $uid=$UC->where("email='".$post['member_email']."' and password='".$post['member_passwd']."'")->getField('uid');
            $uc_username=$UC->where('uid='.$uid)->getField('username');
            //$uc_password=$UC->where('uid='.$uid)->getField('password');
            $uc_usertype=$UC->where('uid='.$uid)->getField('usertype');
            $uc_regdate=$UC->where('uid='.$uid)->getField('regdate');
            //echo $uid;exit;
            //查询是否存在uid 不存在插入 存在则更新
            $count=$Member->where('member_id='.$uid)->count();
            if($count==0){
                //写入
                $data['member_id']=$uid;
                $data['uc_username']=$uc_username;
                $data['member_email']=$post['member_email'];
                $data['member_passwd']=md5($post['password']);
                $data['uc_usertype']=$uc_usertype;
                $data['member_reg_time']=$uc_regdate;
                //print_r($data);exit;
                $Member->post=$data;
                if(!$Member->user_add_post()){
                    echo "<script>alert('同步失败，请您尝试重新提交');history.back(-1);</script>";exit;
                }
            }else{
                //更新本地数据表
                $data['uc_username']=$uc_username;
                $data['member_email']=$post['member_email'];
                $data['member_passwd']=md5($post['password']);
                $data['uc_usertype']=$uc_usertype;
                $Member->where('member_id='.$uid)->save($data);
            }

        }
        $member_id=$Member->where("member_email='".$post['member_email']."'")->getField('member_id');
        //设置session cookie
        session('member_id',$member_id);
        session('member_email',$post['member_email']);
        cookie('member_id',$member_id,3600);
        cookie('member_email',$post['member_email'],3600);
        //推送uc 以后改为异步
        //$post=I('post.');
        vendor('Ucenter.UcApi');//载入UcApi扩展
        //查询与ucenter同步的username
        $data['username']=$Member->where("member_id=".$member_id)->getField('uc_username');
        $data['password']=I('post.member_passwd');
        //echo $data['username'];exit;
        //echo I('post.member_passwd');exit;
        $login = UcApi::login($data);
        if($login===FALSE){
            //如果同步登录失败，要检查uid,username,password是否一致
            echo "<script>alert('同步登录失败');window.location.href='/home/index';</script>";exit;
        }
        echo $login['synlogin'];//输出同步登录代码 （这步很重要）
        echo "<script>window.location.href='/home/index'</script>";exit;
    }
    //退出登录
    public function logout(){
        session('member_id',null);
        session('member_email',null);
        cookie('member_id',null);
        cookie('member_email',null);
        vendor('Ucenter.UcApi');//载入UcApi扩展
        echo UcApi::logout();	//输出同步登出的代码 （这步很重要）
        echo "<script>window.location.href='/home/user/login'</script>";exit;
    }

    //获取36进制用户名 区分本端 member_type 1为本端 2为其他端
    public function get_uc_username(){
        $month_start=mktime(0,0,0,date('m'),1,date('Y'));
        //echo date('Y-m-d H:i:s',$month_start);exit;
        $Model=D("Member");
        $member_total=$Model->field('member_id')->where('uc_usertype=1 and member_reg_time >'.$month_start)->count()+1;
        //echo $member_total;exit;
        $member_total=sprintf("%06d", $member_total);
        $numbers='0'.date('ym',time()).$member_total;
        //echo $numbers;exit;
        if(strlen($numbers)==7){
            $sn='JYB'.$this->noTots($numbers);
        }else{
            $sn='JYB0'.$this->noTots($numbers);
        }
        return $sn;
    }

    //10进制转36进制
    private function noTots($no) {
        $char_array=array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
        while($no >= 36) {
            $rtn = $char_array[fmod($no, 36)].$rtn;
            $no = floor($no/36);
        }
        return $char_array[$no].$rtn;
    }

    //phpMailer 
    public function mailer($email){
        import('Org.Mail');
        $vcode = rand(1000,9999);
        $content = '您的验证码是'.$vcode.'请在10分钟之内完成验证！';
        SendMail($email,'找金银网注册验证',$content,'找金银网');//解释下参数: 参数1---目标邮箱, 参数2----邮件标题,参数三--邮件正文,参数四---发件人名称;
        return $vcode;
    }
    //短信发送
    public function Msg($mobile){
        if(!$_COOKIE['msglife']==1){
            import('Org.Msg');
            $vcode = rand(000000,999999);
            sendmsg($vcode,$mobile);//解释下参数: 参数1---验证码, 参数2----手机号;
            cookie('msglife',1,60);
            return $vcode;
        } else{
            exit;
        }
    }
    //验证码
    public function show_verify(){
        $Verify =     new \Think\Verify();
        $Verify->imageW = 121;  //图片宽
        $Verify->imageH = 53;  //图片高
        $Verify->fontSize =18;  //字体大小
        $Verify->length   = 4;  //字符数
        $Verify->fontttf = '5.ttf';  //字体
        $Verify->expire = 30;  //有效期
        $Verify->useNoise = false;  //不添加杂点
        $Verify->entry();
    }
}